import { useEffect, useRef, useState } from "react";
import { Path, SlotID } from "../constant";
import { IconButton } from "./button";
import { EmojiAvatar } from "./emoji";
import styles from "./my-new-chat.module.scss";
import NextImage from "next/image";

import LeftIcon from "../icons/left.svg";
import LightningIcon from "../icons/lightning.svg";
import EyeIcon from "../icons/eye.svg";
import ConfirmIcon from "../icons/confirm.svg";

import { useLocation, useNavigate } from "react-router-dom";
import { Mask, useMaskStore } from "../store/mask";
import Locale from "../locales";
import { useAppConfig, useChatStore, useNewChatStore } from "../store";
import { MaskAvatar } from "./mask";
import { useCommand } from "../command";
import { showConfirm, Progress } from "./ui-lib";
import { BUILTIN_MASK_STORE } from "../masks";

function MaskItem(props: { mask: Mask; onClick?: () => void }) {
  return (
    <div className={styles["mask"]} onClick={props.onClick}>
      <MaskAvatar
        avatar={props.mask.avatar}
        model={props.mask.modelConfig.model}
      />
      <div className={styles["mask-name"] + " one-line"}>{props.mask.name}</div>
    </div>
  );
}

function useMaskGroup(masks: Mask[]) {
  const [groups, setGroups] = useState<Mask[][]>([]);

  useEffect(() => {
    const computeGroup = () => {
      const appBody = document.getElementById(SlotID.AppBody);
      if (!appBody || masks.length === 0) return;

      const rect = appBody.getBoundingClientRect();
      const maxWidth = rect.width;
      const maxHeight = rect.height * 0.6;
      const maskItemWidth = 120;
      const maskItemHeight = 50;

      const randomMask = () => masks[Math.floor(Math.random() * masks.length)];
      let maskIndex = 0;
      const nextMask = () => masks[maskIndex++ % masks.length];

      const rows = Math.ceil(maxHeight / maskItemHeight);
      const cols = Math.ceil(maxWidth / maskItemWidth);

      const newGroups = new Array(rows)
        .fill(0)
        .map((_, _i) =>
          new Array(cols)
            .fill(0)
            .map((_, j) => (j < 1 || j > cols - 2 ? randomMask() : nextMask())),
        );

      setGroups(newGroups);
    };

    computeGroup();

    window.addEventListener("resize", computeGroup);
    return () => window.removeEventListener("resize", computeGroup);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return groups;
}
// 选择性别
const SelectGenderPage = () => {
  const newChatStore = useNewChatStore();
  const [selectGender, selectCurrent] = useNewChatStore(
    (state) => [
      state.selectGender,
      state.selectCurrent,
    ],
  );
  const SelectBtn = (gender: number) => {
    setTimeout(() => {
      selectGender(gender)
      selectCurrent(newChatStore.current + 1)
      console.log('选择了性别', gender)
      // chatStore.newSession(mask);
      // navigate(Path.Chat);
    }, 10);
  };
  const genderList = [
    {
      name: "男",
      avatar: 1,
    },
    {
      name: "女",
      avatar: 2,
    },
    {
      name: "其他",
      avatar: 0,
    },
  ];
  return (
    <div className={styles["gender-page"]}>
      <div className={styles["title"]}>选着您的性别</div>

      <div className={styles["gender-box"]}>
        {genderList.map((item, i) => (
          <div key={i}
            className={`${styles["gender-item"]} ${newChatStore.gender == item.avatar && styles["gender-active"]}`}
            onClick={() => SelectBtn(item.avatar)}>
            {item.name}
          </div>
        ))}
      </div>
    </div>
  );
}
// 选择兴趣
export function SelectInterestPage() {
  const maskRef = useRef<HTMLDivElement>(null);
  const maskStore = useMaskStore();
  const masks = maskStore.getAll();
  const groups = useMaskGroup(masks);
  const newChatStore = useNewChatStore();
  const [selectInterest, selectCurrent] = useNewChatStore(
    (state) => [
      state.selectInterest,
      state.selectCurrent,
    ],
  );
  // const [interestDate] = useNewChatStore().interestDate;
  const interestDate = [{ id: 1, avatar: "1f4d1", name: '主导' }, { id: 2, avatar: "1f469", name: '内敛' },
  { id: 3, avatar: "1f468", name: '调情' }, { id: 4, avatar: "1f469", name: '逗比' },
  { id: 5, avatar: "1f469", name: '火辣' }, { id: 6, avatar: "1f469", name: '可爱' },
  { id: 7, avatar: "1f469", name: '电视剧' }, { id: 8, avatar: "1f469", name: '健身房' },
  { id: 9, avatar: "1f469", name: '流行摇滚' }, { id: 10, avatar: "1f469", name: '心理医生' },
  { id: 11, avatar: "1f469", name: '搞怪点子王' }, { id: 12, avatar: "1f469", name: '害羞' },
  { id: 13, avatar: "1f469", name: '幽默' }];


  const SelectBtn = (obj: object) => {
    setTimeout(() => {
      selectInterest(obj)
      selectCurrent(newChatStore.current + 1)
      console.log('选择了兴趣', obj)
      // chatStore.newSession(mask);
      // navigate(Path.Chat);
    }, 10);
  };

  return (
    <div className={styles["interest-page"]}>
      <div className={styles["title"]}>你的兴趣</div>

      <div className={styles["interest-box"]}>
        {interestDate.map((item, i) => (
          <div key={i} className={styles["interest-item"]} onClick={() => SelectBtn(item)}>
            <MaskAvatar avatar={item.avatar} />
            <div className={styles["interest-name"] + " one-line"}>{item.name}</div>
          </div>
        ))}
      </div>
    </div>
  )
}
// 选择偏好
import imgurl from "../images/katong.png";
export function SelectPreferencePage() {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  const preferenceDate = [{ id: 1, avatar: "1f4d1", name: '现实' }, { id: 2, avatar: "1f469", name: '超现实主义' },
  { id: 3, avatar: "1f468", name: '日本卡通' }, { id: 4, avatar: "1f469", name: '异次元' }]

  const SelectBtn = (obj: object, index: number) => {
    setTimeout(() => {
      // selectInterest(obj)
      // selectCurrent(newChatStore.current + 1)
      setActiveIndex(index)
      console.log('选择了兴趣', obj, index)
      // chatStore.newSession(mask);
      // navigate(Path.Chat);
    }, 10);
  };
  // const imgurl = '../images/katong.png'

  return (
    <div className={styles["preference-page"]}>
      <div className={styles["title"]}>偏好</div>
      <div className={styles["sub-title"]}>{Locale.NewChat.SubTitle}</div>

      <div className={styles["preference-box"]}>
        {preferenceDate.map((item, i) => (
          <div key={i} className={`${styles["preference-item"]} ${activeIndex === i && styles["preference-active"]}`} onClick={() => SelectBtn(item, i)}>
            <div className={styles["item-title"]}>{item.name}</div>
            <NextImage src={imgurl.src} width={100} height={150} alt="bot" />
            <div className={styles["item-mark"]} style={activeIndex === i ? { display: `flex` } : {}}>
              <ConfirmIcon />
            </div>
          </div>
        ))}
      </div>


    </div>
  )
}
// 选择角色
export function selectRolePage() {
}

export function NewChat() {
  const [selectCurrent, reset] = useNewChatStore(
    (state) => [
      state.selectCurrent,
      state.reset
    ],
  );
  const chatStore = useChatStore();
  const maskStore = useMaskStore();
  const newChatStore = useNewChatStore();
  const masks = maskStore.getAll();
  const groups = useMaskGroup(masks);

  const navigate = useNavigate();
  const config = useAppConfig();

  const maskRef = useRef<HTMLDivElement>(null);

  const { state } = useLocation();

  const startChat = (mask?: Mask) => {
    setTimeout(() => {
      selectCurrent(newChatStore.current + 1)
      console.log('我点击了', newChatStore)
      // chatStore.newSession(mask);
      // navigate(Path.Chat);
    }, 10);
  };


  const nextStep = (mask?: Mask) => {
    setTimeout(() => {
      selectCurrent(newChatStore.current + 1)
      console.log('下一步', newChatStore)
      // chatStore.newSession(mask);
      // navigate(Path.Chat);
    }, 10);
  };
  const prevStep = (mask?: Mask) => {
    setTimeout(() => {
      selectCurrent(newChatStore.current - 1)
      console.log('上一步', newChatStore)
      // chatStore.newSession(mask);
      // navigate(Path.Chat);
    }, 10);
  };
  const successChat = () => {
    setTimeout(() => {
      // selectCurrent(newChatStore.current + 1)
      reset()
      console.log('成功', newChatStore)
      // chatStore.newSession(mask);
      // navigate(Path.Chat);
    }, 10);
  };

  useCommand({
    mask: (id) => {
      try {
        const mask = maskStore.get(id) ?? BUILTIN_MASK_STORE.get(id);
        startChat(mask ?? undefined);
      } catch {
        console.error("[New Chat] failed to create chat from mask id=", id);
      }
    },
  });

  useEffect(() => {
    if (maskRef.current) {
      maskRef.current.scrollLeft =
        (maskRef.current.scrollWidth - maskRef.current.clientWidth) / 2;
    }
  }, [groups]);

  // useEffect(()=>{
  // console.log('newChatStore********',newChatStore)

  // },[newChatStore])

  return (
    <div className={styles["my-new-chat"]}>
      <div className={styles["mask-header"]}>
        <IconButton
          icon={<LeftIcon />}
          text={Locale.NewChat.Return}
          onClick={() => navigate(Path.Home)}
        ></IconButton>
        {/* 不再提示按钮 */}
        {/* {!state?.fromHome && (
          <IconButton
            text={Locale.NewChat.NotShow}
            onClick={async () => {
              if (await showConfirm(Locale.NewChat.ConfirmNoShow)) {
                startChat();
                config.update(
                  (config) => (config.dontShowMaskSplashScreen = true),
                );
              }
            }}
          ></IconButton>
        )} */}
      </div>
      <div className={styles["progress-box"]}>
        <Progress
          percent={Number((newChatStore.current / newChatStore.totol * 100).toFixed(0))}
          trailColor='#fff'
        />
      </div>

      <div className={styles["mask-content"]}>

        {/* 空白页开始 */}
        {newChatStore.current === 0 &&
          (
            <>
              <div className={styles["mask-cards"]}>
                <div className={styles["mask-card"]}>
                  <EmojiAvatar avatar="1f606" size={24} />
                </div>
                <div className={styles["mask-card"]}>
                  <EmojiAvatar avatar="1f916" size={24} />
                </div>
                <div className={styles["mask-card"]}>
                  <EmojiAvatar avatar="1f479" size={24} />
                </div>
              </div>

              <div className={styles["title"]}>{Locale.NewChat.Title}</div>
              <div className={styles["sub-title"]}>{Locale.NewChat.SubTitle}</div>
            </>
          )
        }

        {/* 选着性别 */}
        {newChatStore.current === 1 && <SelectGenderPage />}
        {/* 兴趣 */}
        {newChatStore.current === 2 && <SelectInterestPage />}
        {/* 偏好 */}
        {newChatStore.current === 3 && <SelectPreferencePage />}
        {/* 角色 */}
        {newChatStore.current === 4 &&
          (
            <>

              <div className={styles["title"]}>角色</div>
              <div className={styles["sub-title"]}>{Locale.NewChat.SubTitle}</div>
            </>
          )
        }


        <div>
          当前进度 ： {(newChatStore.current / newChatStore.totol * 100).toFixed(0)}
          <div>
            {/* 当前数据：{JSON.stringify(newChatStore)} */}

          </div>
        </div>

        <div className={styles["actions"]}>
          {/* <IconButton
          text={Locale.NewChat.More}
          onClick={() => navigate(Path.Masks)}
          icon={<EyeIcon />}
          bordered
          shadow
        /> */}
          {newChatStore.current === 0 &&
            (<IconButton
              text={Locale.MyNewChat.Start}
              onClick={() => startChat()}
              icon={<LightningIcon />}
              type="primary"
              shadow
              className={styles["start"]}
            />)
          }
          {(newChatStore.current !== 0 && newChatStore.current != newChatStore.totol) &&
            (
              <>
                <div>
                  <IconButton
                    text={"下一步"}
                    onClick={() => nextStep()}
                    icon={<LightningIcon />}
                    type="primary"
                    shadow
                    className={styles["start"]}
                  />
                </div>
                <div>
                  <IconButton
                    text={"上一步"}
                    onClick={() => prevStep()}
                    icon={<LightningIcon />}
                    type="primary"
                    shadow
                    className={styles["start"]}
                  />
                </div>

              </>
            )
          }
          {newChatStore.current === newChatStore.totol &&
            (
              <>
                <IconButton
                  text={"上一步"}
                  onClick={() => prevStep()}
                  icon={<LightningIcon />}
                  type="primary"
                  shadow
                  className={styles["start"]}
                />
                <IconButton
                  text={"启动"}
                  onClick={() => successChat()}
                  icon={<LightningIcon />}
                  type="primary"
                  shadow
                  className={styles["start"]}
                />
              </>)
          }

        </div>

        {/* <div className={styles["masks"]} ref={maskRef}>
        {groups.map((masks, i) => (
          <div key={i} className={styles["mask-row"]}>
            {masks.map((mask, index) => (
              <MaskItem
                key={index}
                mask={mask}
                onClick={() => startChat(mask)}
              />
            ))}
          </div>
        ))}
      </div> */}
      </div>
    </div>
  );
}
